from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                               QComboBox, QPushButton, QTableWidget, QTableWidgetItem,
                               QLineEdit, QMessageBox, QDialog, QSpinBox, QFrame)
from PySide6.QtCore import Qt
from models.member import Member
from models.service import Service
from utils.db import db


class PaymentDialog(QDialog):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setup_ui()
        self.load_data()
        self.apply_styles()

    def setup_ui(self):
        self.setWindowTitle("收银结算")
        self.setMinimumWidth(500)
        self.setMinimumHeight(400)

        layout = QVBoxLayout(self)
        layout.setSpacing(15)

        # 创建表单区域
        form_frame = QFrame()
        form_frame.setObjectName("formFrame")
        form_layout = QVBoxLayout(form_frame)

        # 创建所有输入控件
        self.member_combo = QComboBox()
        self.service_combo = QComboBox()
        self.staff_combo = QComboBox()
        self.amount_input = QLineEdit()
        self.payment_combo = QComboBox()

        # 设置控件属性
        self.member_combo.setMinimumWidth(250)
        self.service_combo.setMinimumWidth(250)
        self.staff_combo.setMinimumWidth(250)
        self.amount_input.setReadOnly(True)
        self.payment_combo.addItems(["现金", "微信", "支付宝"])

        self.service_combo.currentIndexChanged.connect(self.update_amount)

        # 创建表单行
        member_layout = self.create_form_row("会员：", self.member_combo)
        service_layout = self.create_form_row("服务项目：", self.service_combo)
        staff_layout = self.create_form_row("服务员工：", self.staff_combo)
        amount_layout = self.create_form_row("金额：", self.amount_input)
        payment_layout = self.create_form_row("支付方式：", self.payment_combo)

        # 添加所有行到表单布局
        form_layout.addLayout(member_layout)
        form_layout.addLayout(service_layout)
        form_layout.addLayout(staff_layout)
        form_layout.addLayout(amount_layout)
        form_layout.addLayout(payment_layout)

        # 按钮区域
        button_layout = QHBoxLayout()
        self.save_btn = QPushButton("确认结算")
        self.cancel_btn = QPushButton("取消")

        self.save_btn.setObjectName("primaryButton")
        self.cancel_btn.setObjectName("secondaryButton")

        self.save_btn.clicked.connect(self.save_transaction)
        self.cancel_btn.clicked.connect(self.reject)

        button_layout.addWidget(self.save_btn)
        button_layout.addWidget(self.cancel_btn)

        # 添加到主布局
        layout.addWidget(form_frame)
        layout.addLayout(button_layout)

    def create_form_row(self, label_text, widget):
        """创建表单行"""
        layout = QHBoxLayout()
        label = QLabel(label_text)
        label.setMinimumWidth(80)
        layout.addWidget(label)
        layout.addWidget(widget)
        return layout

    def apply_styles(self):
        self.setStyleSheet("""
            QDialog {
                background-color: #f5f6fa;
            }
            #formFrame {
                background-color: white;
                border-radius: 5px;
                padding: 20px;
            }
            QLabel {
                font-size: 14px;
            }
            QComboBox, QLineEdit {
                padding: 8px;
                border: 1px solid #dcdde1;
                border-radius: 4px;
                min-height: 20px;
            }
            QComboBox:focus, QLineEdit:focus {
                border-color: #5352ed;
            }
            #primaryButton {
                background-color: #5352ed;
                color: white;
                border: none;
                padding: 10px 20px;
                border-radius: 4px;
                min-width: 100px;
            }
            #primaryButton:hover {
                background-color: #3742fa;
            }
            #secondaryButton {
                background-color: #dcdde1;
                border: none;
                padding: 10px 20px;
                border-radius: 4px;
                min-width: 100px;
            }
            #secondaryButton:hover {
                background-color: #c8c9cc;
            }
        """)

    def load_data(self):
        # 加载会员
        members = Member.get_all()
        self.member_combo.addItem("非会员", None)
        for member in members:
            self.member_combo.addItem(f"{member['name']} ({member['phone']})", member['id'])

        # 加载服务项目
        services = Service.get_all()
        for service in services:
            self.service_combo.addItem(
                f"{service['name']} (¥{service['price']:.2f})",
                service
            )

        # 加载员工（只加载员工角色的用户）
        sql = """
        SELECT id, username, display_name 
        FROM users 
        WHERE role = 'staff'
        ORDER BY display_name
        """
        staffs = db.fetch_all(sql)
        for staff in staffs:
            display_text = staff['display_name'] or staff['username']
            self.staff_combo.addItem(display_text, staff['id'])

        # 更新金额
        self.update_amount()

    def update_amount(self):
        service_data = self.service_combo.currentData()
        if service_data:
            self.amount_input.setText(f"¥{service_data['price']:.2f}")

    def save_transaction(self):
        try:
            member_id = self.member_combo.currentData()
            service_data = self.service_combo.currentData()
            staff_id = self.staff_combo.currentData()
            amount = float(self.amount_input.text().replace('¥', ''))
            payment_method = self.payment_combo.currentText()

            if not service_data or not staff_id:
                raise ValueError("请选择服务项目和服务员工")

            # 计算积分（消费金额的10%）
            points_earned = int(amount * 10) if member_id else 0

            # 开始数据库事务
            db.execute("BEGIN TRANSACTION")
            try:
                # 保存交易记录
                sql = """
                INSERT INTO transactions 
                (member_id, service_id, staff_id, amount, payment_method, points_earned)
                VALUES (?, ?, ?, ?, ?, ?)
                """
                db.execute(sql, (member_id, service_data['id'], staff_id,
                                 amount, payment_method, points_earned))

                # 如果是会员，更新会员积分和消费总额
                if member_id:
                    sql = """
                    UPDATE members 
                    SET points = points + ?,
                        total_consumption = total_consumption + ?,
                        last_visit_at = CURRENT_TIMESTAMP
                    WHERE id = ?
                    """
                    db.execute(sql, (points_earned, amount, member_id))

                # 提交事务
                db.execute("COMMIT")
                QMessageBox.information(self, "成功",
                                        f"结算成功！\n{'获得积分：'+str(points_earned) if points_earned else ''}")
                self.accept()

            except Exception as e:
                # 发生错误时回滚事务
                db.execute("ROLLBACK")
                raise e

        except Exception as e:
            QMessageBox.critical(self, "错误", f"结算失败：{str(e)}")


class PaymentPage(QWidget):
    def __init__(self):
        super().__init__()
        # 检查表是否存在
        if not db.table_exists("payments"):
            db.execute("""
                CREATE TABLE payments (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    amount REAL NOT NULL,
                    payment_time DATETIME DEFAULT CURRENT_TIMESTAMP,
                    payment_method TEXT,
                    member_id INTEGER REFERENCES members(id)
                )
            """)
        if not db.table_exists("transactions"):  # 补充transactions表检查
            db.execute("""
                CREATE TABLE transactions (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    member_id INTEGER,
                    service_id INTEGER,
                    staff_id INTEGER,
                    amount DECIMAL(10,2) NOT NULL,
                    payment_method TEXT NOT NULL,
                    points_earned INTEGER DEFAULT 0,
                    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                    FOREIGN KEY (member_id) REFERENCES members(id),
                    FOREIGN KEY (service_id) REFERENCES services(id),
                    FOREIGN KEY (staff_id) REFERENCES users(id)
                )
            """)
        self.setup_ui()
        self.load_transactions()
        self.apply_styles()

    def setup_ui(self):
        # 确保 Widget 可见
        self.setVisible(True)
        self.setMinimumSize(800, 600)  # 设置最小尺寸

        layout = QVBoxLayout(self)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(20)

        # 添加一个测试标签，验证页面是否正常显示
        test_label = QLabel("收银结算页面")
        test_label.setStyleSheet("font-size: 24px; color: red;")
        layout.addWidget(test_label)

        # 顶部工具栏
        toolbar = QFrame()
        toolbar.setObjectName("toolbar")
        toolbar_layout = QHBoxLayout(toolbar)

        # 按钮
        self.new_payment_btn = QPushButton("新增结算")
        self.refresh_btn = QPushButton("刷新")

        self.new_payment_btn.setObjectName("primaryButton")
        self.refresh_btn.setObjectName("secondaryButton")

        self.new_payment_btn.clicked.connect(self.new_payment)
        self.refresh_btn.clicked.connect(self.load_transactions)

        toolbar_layout.addWidget(self.new_payment_btn)
        toolbar_layout.addWidget(self.refresh_btn)
        toolbar_layout.addStretch()

        # 交易记录表格
        self.table = QTableWidget()
        self.table.setObjectName("transactionTable")
        self.table.setColumnCount(8)
        self.table.setHorizontalHeaderLabels([
            "ID", "会员", "服务项目", "服务员工",
            "金额", "支付方式", "获得积分", "时间"
        ])

        # 设置表格样式
        self.table.setSelectionBehavior(QTableWidget.SelectRows)
        self.table.setEditTriggers(QTableWidget.NoEditTriggers)
        self.table.horizontalHeader().setStretchLastSection(True)
        self.table.setAlternatingRowColors(True)

        layout.addWidget(toolbar)
        layout.addWidget(self.table)

    def apply_styles(self):
        self.setStyleSheet("""
            QWidget {
                background-color: white;
            }
            #toolbar {
                background-color: #f8f9fa;
                border-radius: 5px;
                padding: 10px;
            }
            #primaryButton {
                background-color: #5352ed;
                color: white;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
            }
            #primaryButton:hover {
                background-color: #3742fa;
            }
            #secondaryButton {
                background-color: #dcdde1;
                border: none;
                padding: 8px 15px;
                border-radius: 4px;
            }
            #secondaryButton:hover {
                background-color: #c8c9cc;
            }
            #transactionTable {
                border: none;
                gridline-color: #f1f2f6;
            }
            #transactionTable::item {
                padding: 8px;
            }
            #transactionTable::item:selected {
                background-color: #5352ed22;
            }
            QHeaderView::section {
                background-color: #f8f9fa;
                padding: 8px;
                border: none;
                border-bottom: 2px solid #dcdde1;
            }
        """)

    def load_transactions(self):
        """加载交易记录"""
        self.table.setRowCount(0)

        sql = """
        SELECT 
            t.*,
            m.name as member_name,
            m.phone as member_phone,
            s.name as service_name,
            u.display_name as staff_display_name,
            u.username as staff_username
        FROM transactions t
        LEFT JOIN members m ON t.member_id = m.id
        LEFT JOIN services s ON t.service_id = s.id
        LEFT JOIN users u ON t.staff_id = u.id
        ORDER BY t.created_at DESC
        LIMIT 100
        """
        transactions = db.fetch_all(sql)

        for row, trans in enumerate(transactions):
            self.table.insertRow(row)

            # 格式化会员信息
            member_info = "非会员"
            if trans["member_name"]:
                member_info = f"{trans['member_name']} ({trans['member_phone']})"

            # 格式化员工信息
            staff_name = trans["staff_display_name"] or trans["staff_username"]

            # 格式化时间
            created_time = trans["created_at"].split(".")[0]  # 移除毫秒部分

            self.table.setItem(row, 0, QTableWidgetItem(str(trans["id"])))
            self.table.setItem(row, 1, QTableWidgetItem(member_info))
            self.table.setItem(row, 2, QTableWidgetItem(trans["service_name"]))
            self.table.setItem(row, 3, QTableWidgetItem(staff_name))
            self.table.setItem(row, 4, QTableWidgetItem(f"¥{trans['amount']:.2f}"))
            self.table.setItem(row, 5, QTableWidgetItem(trans["payment_method"]))
            self.table.setItem(row, 6, QTableWidgetItem(str(trans["points_earned"])))
            self.table.setItem(row, 7, QTableWidgetItem(created_time))

    def new_payment(self):
        """新增结算"""
        dialog = PaymentDialog(self)
        if dialog.exec_() == QDialog.Accepted:
            self.load_transactions()

    def load_payments(self):
        try:
            payments = db.fetch_all("""
                SELECT 
                    p.id, p.amount, p.payment_time, p.payment_method, p.member_id,
                    m.name as member_name
                FROM payments p
                LEFT JOIN members m ON p.member_id = m.id
            """)
            # ... 后续处理保持不变 ...
        except Exception as e:  # 添加缺失的except块
            QMessageBox.critical(self, "错误", f"加载支付记录失败: {str(e)}")

    def create_payment(self, dialog, amount, method, member_id):
        try:
            if not amount or float(amount) <= 0:
                raise ValueError("请输入有效金额")

            # 执行数据库操作
            db.execute(
                "INSERT INTO payments (amount, payment_method, member_id) VALUES (?, ?, ?)",
                (float(amount), method, member_id)
            )

            # 更新会员余额
            if member_id:
                db.execute(
                    "UPDATE members SET balance = balance - ? WHERE id = ?",
                    (float(amount), member_id)
                )

            dialog.accept()
            self.load_payments()
        except Exception as e:
            QMessageBox.critical(dialog, "错误", str(e))
